<template>
  <div class="article-detail-warp">
    <el-row type="flex" class justify="center">
      <el-col :span="18">
        <div class="article-detail-content-warp">
          <el-row type="flex" class justify="space-between">
            <el-col :span="17">
              <div class="article-detail-left-warp">
                <h1>{{articleDetail.articleTitle}}</h1>
                <div class="article-meta-warp">
                  <span class="article-meta"><i class="fa fa-clock-o"></i> {{articleDetail.createdDate}}</span>
                  <span class="article-meta"><i class="fa fa-eye"></i> {{articleDetail.browseCount}}</span>
                  <span v-for="item in articleTagList" :key="item.tagId" class="article-meta"><i class="el-icon-collection-tag" style="color: #FF69B4;"></i>{{item.tagName}}</span>
                </div>
                <!-- 使用编辑器来显示后端读取来的文章数据 -->
                <mavonEditor
                    class="md"
                    :value="articleDetail.articleMarkDownContent"
                    :subfield = "prop.subfield"
                    :defaultOpen = "prop.defaultOpen"
                    :toolbarsFlag = "prop.toolbarsFlag"
                    :editable="prop.editable"
                    :scrollStyle="prop.scrollStyle"
                    :codeStyle="prop.codeStyle"
                ></mavonEditor>
                
              </div>
              <div class="good-btn-warp">
                <el-button @mouseenter.native="goodBtnMouseEnter()" @mouseleave.native="goodBtnMouseLeave()" round :class="{'good-btn':!isGood,'cancel-good-btn': isGood}" @click="goodBtnClick()"><span v-if="!isGood">点赞 </span><span v-else>{{goodBtnText}}</span><i class="fa fa-thumbs-o-up"></i> {{articleDetail.goodCount}}</el-button>
              </div>
              <div class="article-comment-editor-warp">
                <!-- 子组件向父组件通过自定义组件传值的时候对应的父组件中的处理这个事件的函数只写函数名否则接不到子组件通过载荷传过来的数据 -->
                <articleCommentEditor @articleCommentSubmit="articleCommentSubmit"></articleCommentEditor>
              </div>
              <div class="article-commentList-warp">
                <articleCommentList :commentList="articleCommentData"></articleCommentList>
                <div v-if="moreCommentDataIsShow">
                  <div  v-if="isHaveCommentData" ><el-button class="more-comment-btn" @click="moreCommentBtnClick" type="primary" :loading="isCommentLoading">{{isCommentLoading?"加载中":"点击加载更多"}}</el-button></div>
                  <div v-else><el-button class="have-no-data-info" disabled>已经没有了呀</el-button></div>
                </div>
                
              </div>
            </el-col>
            <el-col :span="6">
              <div class="article-detail-right-warp">
                <sideBar>
                  <template v-slot:sideBarHeader>
                    <div class="author-img-warp">
                      <el-avatar :size="120" fit="fill" :src="authorInfo.userImg"></el-avatar>
                    </div>
                    <div class="author-nickName-warp">
                      <span class="author-nickName" @click="$router.push({name:'PersonalSpace',query:{userId:authorInfo.userId}})">{{authorInfo.userNickName}}</span>
                    </div>
                    <div class="author-fan-warp">
                        <el-button :class="{'fan-btn':!isFan,'cancel-fan-btn':isFan}"  round  size="small" @click="fanBtnClick()" @mouseenter.native="fanBtnMouseEnter()" @mouseleave.native="fanBtnMouseLeave()">
                          <span v-if="!isFan"><i class="el-icon-plus"></i>关注 {{authorInfo.fanNumber}}</span>
                          <span v-else>{{cancelFanMessage}} {{authorInfo.fanNumber}}</span>
                          </el-button>
                    </div>
                  </template>
                  <template v-slot:sideBarMain>
                    <div class="author-discription-warp">
                      <h3 class="author-discription-title">个人简介</h3>
                      <p class="author-discription">{{authorInfo.description}}</p>
                    </div>
                    <div class="author-tags-warp">
                      <h3 class="author-tags-title">文章标签</h3>
                      <div v-if="authorIsReady" class="author-tag-list">
                        <div class="author-tag-list-item" v-for="(item,index) in tagListData" :key="index">
                          <a href="javascript:;" @click="tagClick(item.tagId,authorInfo.userId)">{{item.tagName}}</a>
                        </div>
                      </div>
                      <div v-if="authorIsReady&&moreTagDataIsShow">
                          <el-link @click="moreTagDataLinkClick" :disabled="!isHaveTagListData">{{isHaveTagListData?"加载更多":"已经没有了"}}<i class="el-icon--right" :class="{'el-icon-arrow-down':!tagDataIsLoading,'el-icon-loading':tagDataIsLoading}"></i> </el-link>
                      </div>
                    </div>
                  </template>
                </sideBar>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {request} from '@/network/request.js';
import sideBar from '@/components/sideBar';
import { mavonEditor } from 'mavon-editor';
import articleCommentEditor from '@/components/articleDetailComponents/articleCommentEditor';
import articleCommentList from '@/components/articleDetailComponents/articleCommentList';
export default {
    name:"ArticleDetail",
    components:{
      sideBar,
      mavonEditor,
      articleCommentEditor,
      articleCommentList
    },
    computed: {
      //编辑器的设置
        prop () {
          let data = {
            subfield: false,// 单双栏模式
            defaultOpen: 'preview',//edit： 默认展示编辑区域 ， preview： 默认展示预览区域 
            editable: false,
            toolbarsFlag: false,
            scrollStyle: true,
            codeStyle:"atelier-lakeside-dark"
          }
          return data
        }
      },
    data(){
      return {
        articleTagList:[],
        articleDetail:{},
        authorInfo: {},
        articleCommentData:[],
        tagListData:[],
        isFan:false,  //表示访问这篇文章的人是不是这篇文章作者的粉丝
        cancelFanMessage:"已关注",
        isGood:false,
        goodBtnText:"已点赞",
        commentIndex:0,
        isCommentLoading: false,
        isHaveCommentData:true,
        isHaveTagListData:true,
        tagDataIsLoading:false,
        tagListIndex:0,
        authorIsReady:false,
        moreCommentDataIsShow:false,
        moreTagDataIsShow:false
      }
    },
    methods:{
      moreTagDataLinkClick(){
        this.tagDataIsLoading=true;
        this.tagListIndex++;
        request({
        url:"/tag/tagList/"+this.$route.query.authorId+"/"+this.tagListIndex
        }).then(res=>{
        console.log(res);
        if(res.data.tagList.length>0){
          //拿过来的数据去重
            let obj={};
            this.tagListData=this.tagListData.concat(res.data.tagList).reduce((item,next)=>{
              obj[next.tagId]?"":obj[next.tagId]=true&&item.push(next);
              return item;
            },[]);
                this.tagDataIsLoading=false;
                this.isHaveTagListData=true;
            }else{
                this.tagDataIsLoading=false;
                this.isHaveTagListData=false;
            }
            }).catch(err=>{
                console.log(err);
                this.$message.error('获取数据失败，请稍后再试');
                this.tagDataIsLoading=false;
                this.isHaveTagListData=true;
                this.tagListIndex--;
            })
      },
      goodBtnMouseEnter(){
        if(this.isGood){
          this.goodBtnText="取消点赞";
        }
      },
      goodBtnMouseLeave(){
        if(this.isGood){
          this.goodBtnText="已点赞";
        }
      },
      goodBtnClick(){
        if(this.$store.state.isLogin){
          if(this.isGood){
          //这里进行取消点赞操作
          request({
            url:"/article/cancelGood",
            method:"post",
            data:{
              userId:this.$store.getters.getCurrentUser.userId,//这个用户ID是从Vuex里获得的 点赞之前记得要验证下是否登录 不然这个ID是取不到的
              articleId:this.articleDetail.articleId
            }
          }).then(res=>{
            console.log(res);
            if(res.data.status==="success"){
              this.isGood=!this.isGood;
              this.articleDetail.goodCount=res.data.goodCount;
              this.$message({
                message: '取消点赞成功> <',
                type: 'success'
                });
            }else{
              this.$message({
                message: '取消点赞出错请稍后再试',
                type: 'warning'
                });
            }
          }).catch(err=>{
            this.$message.error('服务器出错，请稍后再试');
          })
        }else{
            //这里进行点赞操作
            request({
              url:"/article/good",
              method:"post",
              data:{
                userId:this.$store.getters.getCurrentUser.userId,//这个用户ID是从Vuex里获得的 点赞之前记得要验证下是否登录 不然这个ID是取不到的
                articleId:this.articleDetail.articleId
              }
            }).then(res=>{
              console.log(res);
              if(res.data.status==="success"){
                this.isGood=!this.isGood;
                this.goodBtnText="已点赞";
                this.articleDetail.goodCount=res.data.goodCount;
                this.$message({
                message: '点赞成功> <',
                type: 'success'
                });
              }else{
              this.$message({
                message: '点赞操作出错请稍后再试',
                type: 'warning'
                });
            }
            }).catch(err=>{
              console.log(err);
              this.$message.error('服务器出错，请稍后再试');
            })
            
        }
        }else{
          this.$router.replace("/login");
        }
        
      },
      fanBtnClick(){
        if(this.$store.state.isLogin){
          if(this.isFan){
          //这里执行取消关注操作
          request({
            url:"/user/cancelFanAuthor",
            method:"post",
            data:{
              userId:this.$store.getters.getCurrentUser.userId,//这里的用户ID是从vuex里获得的 执行关注之前记得要验证一下是否已经登录了
              authorId:this.authorInfo.userId
            }
          }).then(res=>{
            console.log(res);
             if(res.data.status==="success"){
              this.isFan=!this.isFan;
              this.authorInfo.fanNumber=res.data.fanNumber;
              this.$message({
                message: '取消关注成功> <',
                type: 'success'
                });
            }else{
              this.$message({
                message: '取消关注出错请稍后再试',
                type: 'warning'
                });
            }
          }).catch(err=>{
            console.log(err);
            this.$message.error('服务器出错，请稍后再试');
          })
        }else {
          //这里执行关注该作者操作
          request({
            url:"/user/fanAuthor",
            method:"post",
            data:{
              userId:this.$store.getters.getCurrentUser.userId,//这里的用户ID是从vuex里获得的 执行关注之前记得要验证一下是否已经登录了
              authorId:this.authorInfo.userId
            }
          }).then(res=>{
            console.log(res);
            if(res.data.status==="success"){
              this.isFan=!this.isFan;
              this.cancelFanMessage="已关注";
              this.authorInfo.fanNumber=res.data.fanNumber;
              this.$message({
                message: '关注成功> <',
                type: 'success'
                });
            }else{
              this.$message({
                message: '关注出错请稍后再试',
                type: 'warning'
                });
            }
          }).catch(err=>{
            console.log(err);
            this.$message.error('服务器出错，请稍后再试');
          })
        }
        }else{
          this.$router.replace("/login");
        }
        
        //重新获取下用户信息
      },
      fanBtnMouseEnter(){
        if(this.isFan){
          this.cancelFanMessage="取消关注";
        }
      },
      fanBtnMouseLeave(){
        if(this.isFan){
          this.cancelFanMessage="已关注";
        }
      },
      tagClick(tagId,authorId){
        //点击了某个TAG
        // console.log(tagId+" 作者ID："+authorId);
        this.$router.replace({
          name:"ArticleListByTag",
          query:{
            tagId:tagId,
            authorId:authorId
          }
        })
      },
      articleCommentSubmit(commentText){
        //这里进行评论得提交
        const loading = this.$loading({
                        lock: true,
                        text: '操作中',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                        });
        request({
          url:"/comment/saveArticleComment",
          method:"post",
          data:{
            userId:this.$store.getters.getCurrentUser.userId, //这是要从VUex里拿的已经登录后的用户ID
            articleId:this.articleDetail.articleId,
            articleComment:commentText
          }
        }).then(res=>{
          console.log(res);
          if(res.data.status==="ok"){
            loading.close();
            this.$message({
          message: '>_<评论成功>_<',
          type: 'success'
          });
          this.articleCommentData.unshift(res.data.newComment);
          }else{
            loading.close();
            this.$message.error('提交数据失败，您可能已经评论过该篇文章了');
          }       
        }).catch(err=>{
          console.log(err);
          loading.close();
          this.$message.error('提交数据失败，请稍后再试');
        })
      },
      moreCommentBtnClick(){
        this.isCommentLoading=true;
        this.commentIndex++;
        request({
          url:"/comment/articleComment/"+this.articleDetail.articleId+"/"+this.commentIndex,
        }).then(res=>{
          // console.log(res);
          let obj={};
          if(res.data.articleCommentList.length>0){
            this.articleCommentData=this.articleCommentData.concat(res.data.articleCommentList).reduce((item,next)=>{
              obj[next.commentId]?"":obj[next.commentId]=true&&item.push(next);
                            return item;
            },[]);
            this.isCommentLoading=false;
            this.isHaveCommentData=true;
          }else{
            this.isCommentLoading=false;
            this.isHaveCommentData=false;
          }
        }).catch(err=>{
          console.log(err);
          this.$message.error('获取数据失败，请稍后再试');
          this.isCommentLoading=false;
          this.isHaveCommentData=true;
          this.commentIndex--;
        })
      }
    },
    created(){
      request({
        url:"/article/articleDetail/"+this.$route.query.articleId
      }).then(res=>{
        //  console.log(res);
        this.articleDetail=res.data.articleDetail;
        request({
          url:"/comment/articleComment/"+this.articleDetail.articleId+"/"+this.commentIndex,
        }).then(res=>{
          // console.log(res);
          this.articleCommentData=res.data.articleCommentList;
          if(res.data.articleCommentList.length>=7){
            this.moreCommentDataIsShow=true;
          }
        }).catch(err=>{
          console.log(err);
          this.$message.error('获取数据失败，请稍后再试');
        })
      }).catch(err=>{
        console.log(err);
        this.$message.error('获取数据失败，请稍后再试');
      })
      request({
          url:"/user/userInfo/"+this.$route.query.authorId
        }).then(res=>{
          // console.log(res);
          this.authorInfo=res.data.userInfo;
          this.authorIsReady=true;
        }).catch(err=>{
          console.log(err);
          this.$message.error('获取数据失败，请稍后再试');
        })
        if(this.$store.state.isLogin){
          request({
            url:"/user/userIsFanAndArticleIsGood/"+this.$store.getters.getCurrentUser.userId+"/"+this.$route.query.authorId+"/"+this.$route.query.articleId
          }).then(res=>{
            console.log(res);
            this.isFan=res.data.userIsFan;
            this.isGood=res.data.articleIsGood;
          }).catch(err=>{
            console.log(err);
          })
        }
        request({
          url:"/tag/tagList/"+this.$route.query.authorId+"/0"
        }).then(res=>{
          this.tagListData=res.data.tagList;
          if(res.data.tagList.length>=6){
            this.moreTagDataIsShow=true;
          }
        }).catch(err=>{
          console.log(err);
        })
        request({
          url:"/article/addBrowseNumber",
          method:"post",
          data:{
            articleId:this.$route.query.articleId
          }
        }).then(res=>{
          if(res.data.status==="ok"){
            console.log("浏览量+1");
          }else{
            console.log("浏览量添加失败");
          }
        }).catch(err=>{
          console.log(err);
        })
        request({
          url:"/tag/articleTag/"+this.$route.query.articleId
        }).then(res=>{
          this.articleTagList=res.data.articleTagList;
        }).catch(err=>{
          console.log(err);
        })
    }
}
</script>

<style>
.article-detail-content-warp {
  margin: 20px 0;
}
.article-detail-left-warp {
  min-height: 900px;
}
.article-detail-right-warp {
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    padding: 20px;
    min-height: 900px;
}
.author-img-warp,.author-nickName-warp,.author-fan-warp {
  display: flex;
  justify-content: center;
  padding-bottom: 10px;
}
.author-nickName {
  font-size: 20px;
  color: #666;
  transition: all 0.3s;
}
.author-nickName:hover {
  color: #00c3ff;
  cursor: pointer;
}
.good-btn-warp {
  padding: 20px 0;
  display: flex;
  justify-content: flex-end;
}
.fan-btn,.good-btn,.cancel-good-btn {
  border-color: #FF69B4;
  color: #FF69B4;
}
.fan-btn:hover,.good-btn:hover {
  background-color: #FF69B4;
  color: #fff;
}
.cancel-fan-btn{
  color: #666;
  border-color: #666;
}
.cancel-fan-btn:hover,.cancel-good-btn:hover {
  background-color: #666;
  color: #fff;
  border-color: #666;
}
.cancel-fan-btn:focus {
  color: #fff;
  border-color: #666;
  background-color: #666;
}

.author-discription-title,.author-tags-title {
  padding-left: 10px;
  border-left: 5px solid #FF69B4;
  font-size: 20px;
}
.author-discription {
  color: #666;
  padding: 10px 0;
}

.author-tag-list-item {
  padding: 10px 0;
}
.author-tag-list-item a {
  color: rgb(81, 165, 204);
  font-size: 20px;
  transition: all 0.3s;
}
.author-tag-list-item a:hover {
  color: #FF69B4;
}
.article-meta-warp {
  padding: 20px 0;
}
.article-meta {
  padding: 10px 10px;
  color: #666;
}
.more-comment-btn,.have-no-data-info {
  width: 100%;
}
</style>